package network;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:TCP客户端
 * User: 东莞呵呵
 * Date:2022-10-06
 * Time:8:46
 */
public class TcpEchoClient {
    private Socket socket = null;

    public TcpEchoClient(String serverIP, int post) throws IOException {
        //此处的IP和端口不是给客户端程序指定端口而是和服务器指定的IP和端口建立连接
        this.socket = new Socket(serverIP, post);
    }

    public void start() throws IOException {
        Scanner in = new Scanner(System.in);
        try (InputStream inputStream = socket.getInputStream()) {
            try (OutputStream outputStream = socket.getOutputStream()) {
                while (true) {
                    //1、根据读取的字符串构造请求
                    System.out.print("-> ");
                    String request = in.next();
                    //2、把请求发送给服务器
                    PrintWriter printWriter = new PrintWriter(outputStream);
                    printWriter.println(request);
                    printWriter.flush();
                    //3、接收服务器的响应
                    Scanner inputScanner = new Scanner(inputStream);
                    String response = inputScanner.next();
                    //4、解析响应
                    System.out.println("响应为：" + response);
                }
            }
        }


    }

    public static void main(String[] args) throws IOException {
        TcpEchoClient client = new TcpEchoClient("127.0.0.1", 9090);
        client.start();
    }
}
